#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import json
from generaldb.gbase8a import LOGGER

from common.parse_parafile import ParamFileUtil
from validation.common.json_util import find_all_value_by_key
from validation.validator import ParamValidator


class JsonParam:

    @staticmethod
    def parse_param_with_jsonschema(pid):
        # gbase8a的参数校验路径
        path = "generaldb/gbase8a/jsonschema/gbase8a_base_define.json"
        # 需要二次单独校验的参数路径
        agent_applications_jsonschema_path = "generaldb/gbase8a/jsonschema/gbase8a_agent_applications_define.json"
        cluster_info_jsonschema_path = "generaldb/gbase8a/jsonschema/gbase8a_cluster_info_define.json"
        script_conf_jsonschema_path = "generaldb/gbase8a/jsonschema/gbase8a_script_conf_define.json"

        file_content = ParamFileUtil.parse_param_file_and_valid_by_schema(pid, path)

        # 校验agent_applications
        agent_applications_list = find_all_value_by_key(file_content, "agent_applications")
        for agent_applications in agent_applications_list:
            ParamValidator.valid_data_by_schema(json.loads(agent_applications), agent_applications_jsonschema_path)

        # 校验cluster_info
        cluster_info_list = find_all_value_by_key(file_content, "cluster_info")
        for cluster_info in cluster_info_list:
            cluster_info_json = json.loads(cluster_info)
            # 消除 \x1b[31m\x1b[0m，适配升级场景
            for node_info in cluster_info_json.get('nodes', []):
                status = node_info.get('gcluster_status', '')
                if '\x1b[31m\x1b[0m' in status:
                    node_info['gcluster_status'] = status.replace('\x1b[31m\x1b[0m', '').strip()
            ParamValidator.valid_data_by_schema(cluster_info_json, cluster_info_jsonschema_path)

        # 校验script_conf
        script_conf_list = find_all_value_by_key(file_content, "scriptConf")
        for script_conf in script_conf_list:
            ParamValidator.valid_data_by_schema(json.loads(script_conf), script_conf_jsonschema_path)

        LOGGER.info("Param is valid!")

        return file_content
